﻿using System;
using Castle.Core.Interceptor;
using NHibernate;
using NHibernate.Context;
using IInterceptor=Castle.Core.Interceptor.IInterceptor;

namespace DMS.DAOs.NH.Castle
{
    public class SessionInterceptor : IInterceptor
    {
        private readonly ISessionFactory sessionFactory;

        public SessionInterceptor(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }

		public void Intercept(IInvocation invocation)
		{
			using (new CurrentSessionBinding(sessionFactory))
			{
				invocation.Proceed();
			}
		}

    }

	public class CurrentSessionBinding : IDisposable
	{
		private readonly ISessionFactory sessionFactory;
		public CurrentSessionBinding(ISessionFactory sessionFactory)
		{
			this.sessionFactory = sessionFactory;
			
			ISession session = sessionFactory.OpenSession();
			CurrentSessionContext.Bind(session);
		}

		public void Dispose()
		{
			ISession session = sessionFactory.GetCurrentSession();
			
			session.Flush();
			session.Close();

			CurrentSessionContext.Unbind(sessionFactory);
		}
	}
}